<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href='https://unpkg.com/boxicons@2.1.2/css/boxicons.min.css' rel='stylesheet'>
    <script src="static/js/vue.min.js"></script>
    <script src="static/js/axios.min.js"></script>
    <script src="https://kit.fontawesome.com/bb97f7b388.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="static/css/category.css">
    <link rel="stylesheet" href="static/css/sidebar.css">
    <script src="static/js/app.js"></script>
    <title>花瓣 | 评分</title>
</head>

<body>

    <div class="blocks" id="app">
        <!-- navbar -->
        <div class="nav" id="nav">
            <nav class="nav_content">
                <a href="#" class="nav_logo">
                    <i class='bx'>
                        <img src="static/img/Icon.png" alt="" style="width: 45px; height: 40px;">
                    </i>
                    <span class="nav_logo-name">花瓣</span>
                </a>
                <div class="nav_list">
                    <a href="/vscf/index.html" class="nav_link  ">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">首页</span>
                    </a>
                    <a class="nav_link active-link" href="#">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">分类</span>
                    </a>
                    <a class="nav_link" href="/vscf/my.html">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">我的</span>
                    </a>

                    <div class="sidebar-line"></div>
                    
                    <a class="nav_link" href="/vscf/us.html">
                        <i class='bx bxs-conversation'></i>
                        <span class="nav_name">关于我们</span>
                    </a>
                    <a href="javascript:void(0);" class="nav_link" @click="logout();">
                        <i class='bx bxs-log-in'></i>
                        <span class="nav_name">登出</span>
                    </a>
                </div>
            </nav>
             <footer class="footer" style="display:flex;flex-direction: column;justify-content: center;align-items: baseline;width: 203px;"><div class="footer-line">Powered By Cross Fire • © 2024</div></footer>
        </div>

        <!-- middle block -->
        <section class="middle">
            <div class="header">
                <div class="search">
                    <div class="search-flex">
                        <button type="submit" class="search-button">
                            <i class='bx bx-search'></i>
                        </button>
                        <input type="text" v-model="searchTerm" class="search-term" placeholder="Search...">
                    </div>
                </div>

                <div class="profile-count">
                    <i class='bx bxs-plus-circle'></i>
                    <i class='bx bxs-bell'></i>
                    <a href="/vscf/my.html">
                        <img class="profile-photo" src="static/img/Icon.png" alt="Profile Photo">
                    </a>
                </div>
            </div>

            <div class="merge">
                <div class="post" style="width: 100%;">
                    <div class="community-forums">
                        <div class="cf-title">
                            <i class='bx bxs-conversation'></i>
                            <p class="cf-title-text">分类</p>
                        </div>

                        <div class="cf-tags">
                            <a href="#" class="tags-count" @click.prevent="loadAllCategories">
                                <p class="tags-name">全部</p>
                            </a>
                            <a href="#" class="tags-count" v-for="category in categories" :key="category.id"
                                @click.prevent="onCategoryClick(category)">
                                <p class="tags-name">{{ category.categoryname }}</p>
                            </a>
                        </div>


                        <div class="cf-topics">
                            <div v-if="filteredTopics.length > 0">
                                <div v-for="topic in filteredTopics" :key="topic.works.worksid" class="cf-topics-count" style="display: grid; grid-template-columns: 0.8fr 0.2fr;">
                                    <div class="cf-topics-texts" @click="goToDetails(topic.works.worksid)">
                                        <div class="cf-topics-icon-1" style="display: flex; justify-content: center; align-items: center;">
                                            <!-- 修改这里，确保使用正确的 img 字段 -->
                                            <img :src="topic.img" alt="" style="width: 180px; height: 80px; border-radius: 5px;">
                                        </div>
                                        <div class="cft-text">
                                            <p class="cf-topic-name">{{ topic.works.title }}</p>
                                            <p class="forum-type">{{ topic.works.introduction }}</p>
                                        </div>
                                    </div>
                                    <div style="display: flex; flex-direction: column;">
                                        <div class="cf-topic-reactions" style="justify-content: flex-end;">
                                            <div class="cf-topic-threads">
                                                <p style="font-size: 15px;">浏览量</p>
                                                <p class="threads-amount">{{ topic.works.viewcount || 'N/A' }}</p>
                                            </div>
                                            <div class="cf-topic-messages">
                                                <p style="font-size: 15px;">评分</p>
                                                <p class="messages-amount">{{ topic.score || 'N/A' }}</p>
                                            </div>
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <p style="display: flex; justify-content: flex-end;">发布日期</p>
                                            <p style="display: flex; justify-content: flex-end;">{{ topic.works.date }}</p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div v-else>
                                <p>No topics available for this category.</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

    </div>

    <script>
        new Vue({
            el: '#app',
            data() {
                return {
                    topics: [], // 存储作品列表
                    categories: [], // 存储分类信息
                    searchTerm: '', // 存储搜索关键词
                };
            },
            created() {
                this.checkUserSession();
           
            },
            methods: {
                async initWorks() {
                    const url = '/vscf/works/all'; // 数据接口URL
                    try {
                        const response = await axios.get(url);
                        console.log('Response Data:', response.data); // 打印返回的数据

                        // 解析返回数据并确保每个作品包含评分信息
                        if (Array.isArray(response.data)) {
                            this.topics = response.data.map(item => {
                                let img = item.works.img;
                                let primaryImage = '';

                                // 检查 img 是否包含多个路径（逗号分隔），否则是单个有效 URL
                                if (img) {
                                    // 如果是逗号分隔的路径，取第一个路径
                                    if (img.includes(',')) {
                                        primaryImage = img.split(',')[0].trim(); // 去除可能存在的空格
                                    } else if (img.match(/\.(jpeg|jpg|png|gif)$/)) {
                                        // 如果 img 是有效的图片路径
                                        primaryImage = img;
                                    } else {
                                        primaryImage = ''; // 如果 img 无效，设置为空或默认图片
                                    }
                                } else {
                                    primaryImage = ''; // 如果 img 为空，设置为空或默认图片
                                }

                                return {
                                    works: item.works,
                                    img: primaryImage,  // 获取处理后的图片路径
                                    score: item.score ? item.score.score : 'N/A',  // 如果评分为空，使用 'N/A'
                                };
                            });
                            console.log('Processed Topics:', this.topics); // 打印处理后的数据
                        } else {
                            console.error('返回数据不是数组格式');
                        }
                    } catch (error) {
                        console.error('请求数据失败:', error);
                    }
                }

                ,


                loadAllCategories() {
                    this.searchTerm = '';  // 清空搜索
                    this.initWorks();  // 重新加载所有作品
                },

                async fetchCategories() {
                    const url = '/vscf/works/categories';
                    try {
                        const response = await fetch(url);
                        if (response.ok) {
                            const data = await response.json();
                            console.log('分类数据:', data);  // 打印分类数据，检查是否正确返回
                            this.categories = data;
                        } else {
                            console.error('分类数据加载失败');
                        }
                    } catch (error) {
                        console.error('网络请求失败:', error);
                    }
                },

                async onCategoryClick(category) {
                    console.log('点击的分类:', category);  // 打印选中的分类
                    try {
                        const response = await axios.get('/vscf/works/category', {
                            params: { categoryid: category.id }
                        });

                        if (Array.isArray(response.data)) {
                            console.log('分类作品数据:', response.data);  // 打印返回的作品数据
                            this.topics = response.data.map(item => ({
                                works: item.works,
                                score: item.score ? item.score.score : 'N/A'
                            }));
                        } else {
                            console.error('返回的作品数据不是数组格式');
                        }
                    } catch (error) {
                        console.error('加载分类作品失败:', error);
                    }
                },

                logout() {
                    axios.post('/vscf/user/logout')
                        .then(response => {
                            localStorage.removeItem('userToken');
                            sessionStorage.removeItem('userToken');
                            window.location.href = '/vscf/';
                        })
                        .catch(error => {
                            console.error('登出失败:', error);
                        });
                },
                goToDetails(topicId) {
                    window.location.href = `/vscf/particulars.html?id=${topicId}`;
                },
                checkUserSession() {
                    axios.get('/vscf/user/getSessionUser')
                        .then(response => {
                            if (response.data.success && response.data.user) {
                                this.initWorks(); // 页面创建时加载作品数据
                                this.fetchCategories(); // 页面创建时加载分类数据
                            } else {
                                window.location.href = '/vscf/login.html';
                            }
                        })
                        .catch(error => {
                            console.error('Error fetching user session:', error);
                            window.location.href = '/vscf/login.html';
                        });
                }
            },

            computed: {
                filteredTopics() {
                    return this.topics.filter(topic =>
                        // 确保 topic 和 topic.works 存在再进行过滤
                        topic.works && topic.works.title && topic.works.introduction &&
                        (
                            topic.works.title.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
                            topic.works.introduction.toLowerCase().includes(this.searchTerm.toLowerCase())
                        )
                    );
                }
            }
        });
    </script>

</body>

</html>